package com.ht.baselibs.retrofit.converter.fastjson;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONReader;
import com.ht.baselibs.bean.BaseErrorBean;
import com.ht.baselibs.bean.BaseGetBean;
import com.ht.baselibs.core.EventCenter;
import com.ht.baselibs.core.EventCode;
import com.ht.baselibs.utils.AppAesUtil;
import com.ht.baselibs.utils.LogUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;

import de.greenrobot.event.EventBus;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by WayneSuper on 25/01/2016.
 */
public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private Type type;


    public FastJsonResponseBodyConverter(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody responseBody) throws IOException {
        try {
            String responseStr = responseBody.string();
            String result = responseStr.substring(0, responseStr.length());
            LogUtils.error(result);

            BaseGetBean baseGetBean = JSON.parseObject(result, BaseGetBean.class);
            BaseErrorBean baseErrorBean = JSON.parseObject(result, BaseErrorBean.class);

            if (baseGetBean.resultCode != 1000) {
                // TODO: 2017/5/2 查找原因
                UIUtils.showToast(baseGetBean.resultMessage);

                if (baseGetBean.resultCode == 2026) {

                }
                if (baseGetBean.resultCode == 2041) {//登陆超时
                    SharedPreferencesUtils.put("access_Token", "");

                }
                if (baseGetBean.resultCode == 2040) {  //用户未登陆
                    EventBus.getDefault().post(new EventCenter(EventCode.HSY_REQUEST_CODE_UNLOGIN, baseGetBean.resultMessage));
                }

                return (T) baseErrorBean;
            }
            String access_token = SharedPreferencesUtils.getString("access_Token", "");

            if (TextUtils.isEmpty(access_token)) {
                UIUtils.showToast("未知异常,退出应用后重试");
                return (T) baseGetBean;
            }
            try {
                String decodeResult = AppAesUtil.decryptCBC_NoPaddingFromBase64String(baseGetBean.encryptDataResult, "utf-8",
                        access_token.substring(0, 16), access_token.substring(16, 32));

                JSONReader reader = new JSONReader(new StringReader(decodeResult));
                return reader.readObject(type);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return (T) baseGetBean;
        } finally {
            responseBody.close();
        }
    }

    public interface DecodeService {
        String decode(String data);
    }

}